package com.serverlite.system.module.service;

import org.json.JSONArray;
import org.json.JSONObject;

import com.serverlite.framework.dao.core.Dao;

public class ModuleService {

    /**
     * 获取管理员模块树
     */
    public static JSONArray adminTree(String id){
        try{
            JSONArray node = Dao.select("select * from system_module where pid=? order by sort_num asc",id);
            for(int i = 0; i < node.length(); i++){
                JSONObject o = node.getJSONObject(i);
                String _id = o.getString("id");
                JSONArray children = adminTree(_id);
                o.put("children", children);
            }
            return node;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取模块树
     */
    public static JSONArray tree(String id){
        try{
            JSONArray node = Dao.select("select * from system_module where pid=? and `show`=? order by sort_num asc",id, "true");
            for(int i = 0; i < node.length(); i++){
                JSONObject o = node.getJSONObject(i);
                String _id = o.getString("id");
                JSONArray children = tree(_id);
                o.put("children", children);
            }
            return node;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 加载权限树
     */
    public static JSONArray permissionTree(String id, String roleIds) {
        String modules = (String) Dao
            .queryScalar("select group_concat(module_ids) modules from system_role where id" + Dao.in(roleIds.split(",")));
        return tree(id, Dao.in(modules.split(",")));
    }

    /**
     * 从模块集合中加载模块树 
     */
    public static JSONArray tree(String id, String modules) {
        try {
            JSONArray node = Dao.select(
                "select * from (select * from system_module where id" + modules + ") temp where temp.pid=? and temp.show=? order by sort_num asc", id, "true");
            for (int i = 0; i < node.length(); i++) {
                JSONObject o = node.getJSONObject(i);
                String _id = o.getString("id");
                JSONArray children = tree(_id, modules);
                o.put("children", children);
            }
            return node;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static JSONArray list(){
        return Dao.select("select * from system_module where `show`='true'");
    }
}
